package com.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import javax.sound.midi.Soundbank;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.UUID;

/**
 * Created by xiao zeng on 2017/6/28.
 */

@WebServlet("/serupload.action") @MultipartConfig //servlet3.0 内置tomcat上传
public class Upload extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");

        String useername = req.getParameter("user");//获取表单值
        System.out.println(useername);

       Collection<Part> coll = req.getParts();
       for (Part p :coll){
           String nname = "";
           String name = p.getHeader("content-disposition");//获取属性
           if(name.contains("filename=\"")){
               nname = name.substring(name.lastIndexOf("=\"")+2,name.length()-1);//截取文件名
           }

           if (!nname.equals("")){
              String path = req.getSession().getServletContext().getRealPath("/upload/servletupload");//创建文件夹
              File fi = new File(path);
              if (!fi.exists()){
                  fi.mkdirs();
              }

              String ext = nname.substring(nname.lastIndexOf(".")+1).toLowerCase();//获取后缀名不加点
               System.out.println(ext);
              String uuname = UUID.randomUUID().toString()+"."+ext;
             p.write(path+"/"+uuname);//上传到指定文件夹
          }
       }
    }
}
